const API = require('common/constant.js');
const util = require('utils/util');
const QQMapWX = require('./utils/qqmap-wx-jssdk.js');
var WebIM = require('./utils/WebIM.js')
var WebIM = WebIM.default
App({
  globalData: {},
  onLaunch: function () {
    this.setMyLocation();
    this.login();
    this.listenWeb();
  },
  listenWeb: function (){
    let that = this;
    WebIM.conn.listen({
      onOpened: function (message) {
        WebIM.conn.setPresence();
        console.log("onOpened接口回调", message)
      },
      onTextMessage: function (message) {
        console.log('收到文本', message);
        var pageChat = that.getRoomPage("pages/chat/chat");
        var pageNews = that.getRoomPage('pages/news/news');
        if (message) {
          if (pageChat) {
            pageChat.receiveMsg(message, 'txt')
          } else if (pageNews) {
            pageNews.receiveMsg(message, 'txt')
          } else {
            let valuea = WebIM.parseEmoji(message.data.replace(/\n/mg, ''));
            console.log(message.ext.time, message.id)
            let msgData = {
              'info': {
                'from': ['message.from'],
                'to': ['message.to']
              },
              'myName': ['message.from'],
              'yourname': ['message.to'],
              'msg': {
                'type': 'txt',
                'data': valuea
              },
              'style': '',
              'time': message.ext.time,
              'mid': 'txt' + message.id
            };
            var chatMemberName = 'from' + message.from + "to" + message.to;
            var chatMsgObj = wx.getStorageSync(chatMemberName) || {};
            var chatMsg = chatMsgObj.chatMsg || [];
            chatMsg.push(msgData);

            let noSeeCount = chatMsgObj.noSeeCount || 0;
            const chatMsgCache = {
              yourNickname: message.ext.nickname,
              yourHeadImgUrl: message.ext.headImgUrl,
              yourname: message.from,
              chatMsg: chatMsg,
              noSeeCount: noSeeCount + 1
            };
            wx.setStorage({
              key: chatMemberName,
              data: chatMsgCache,
            })
            that.setChatMemberListCache(chatMemberName);
          }
        }
      },
      onEmojiMessage: function (message) {
        console.log('onEmojiMessage', message)
        var pageChat = that.getRoomPage('pages/chat/chat');
        var pageNews = that.getRoomPage('pages/news/news');
        if (message) {
          if (pageChat) {
            pageChat.receiveMsg(message, 'emoji');
          } else if (pageNews) {
            pageNews.receiveMsg(message, 'emoji');
          } else {
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              myName: message.from,
              yourname: message.to,
              msg: {
                type: 'emoji',
                data: message.data
              },
              style: '',
              time: message.ext.time,
              mid: 'emoji' + message.id
            };
            msgData.style = '';

            var chatMemberName = 'from' + message.from + "to" + message.to;
            var chatMsgObj = wx.getStorageSync(chatMemberName) || {};
            var chatMsg = chatMsgObj.chatMsg || [];
            chatMsg.push(msgData);
            let noSeeCount = chatMsgObj.noSeeCount || 0;            
            const chatMsgCache = {
              yourNickname: message.ext.nickname,
              yourHeadImgUrl: message.ext.headImgUrl,
              yourname: message.from,
              chatMsg: chatMsg,
              noSeeCount: noSeeCount + 1
            }

            wx.setStorage({
              key: chatMemberName,
              data: chatMsgCache,
            })
            that.setChatMemberListCache(chatMemberName);
          }
        }
      },
      onPictureMessage: function (message) {
        var pageChat = that.getRoomPage('pages/chat/chat');
        var pageNews = that.getRoomPage('pages/news/news');
        if (message) {
          if (pageChat) {
            pageChat.receiveImage(message, 'img');
          } else if (pageNews) {
            pageNews.receiveImage(message, 'img');
          } else {
            console.log(message, '2222')
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              myName: message.from,
              yourname: message.to,
              msg: {
                type: 'img',
                data: message.url
              },
              style: '',
              time: message.ext.time,
              mid: 'img' + message.id
            };
            console.log('2222')
            var chatMemberName = 'from' + message.from + 'to' + message.to;
            var chatMsgObj = wx.getStorageSync(chatMemberName) || {};
            var chatMsg = chatMsgObj.chatMsg || [];
            let noSeeCount = chatMsgObj.noSeeCount || 0;            

            chatMsg.push(msgData);

            const chatMsgCache = {
              yourNickname: message.ext.nickname,
              yourHeadImgUrl: message.ext.headImgUrl,
              yourname: message.from,
              chatMsg: chatMsg,
              noSeeCount: noSeeCount + 1              
            }
            wx.setStorage({
              key: chatMemberName,
              data: chatMsgCache,
            })
            that.setChatMemberListCache(chatMemberName);
          }
        }
      },
      onError: function (error) {
        console.log("失败回调", error);
        WebIM.conn.close();
        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
          if (WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax) {
            return;
          }
          wx.showToast({
            title: '失去网络连接，将回到首页',
            duration: 1000
          });
          wx.redirectTo({
              url: '../index/index'
          });
          return;
        }

        // 8: offline by multi login
        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
          wx.showToast({
            title: '您的账号在其他设备登录',
            duration: 2000,
            success() {
              setTimeout(() => {
                wx.redirectTo({
                  url: '../loginAndRegister/loginAndRegister'
                })
              }, 2000)
            }
          })
          return;
        }
      },
    })
  },
  //微信登陆，调用接口，获取用户信息
  login: function (callback) {
    console.log('调用wx.login')
    let that = this;
    wx.login({
      success: res => {
        // console.log('app.js微信登陆获取用户code:',res.code)
        if (res.code) {
          var code = res.code;
          // 查看是否授权
          wx.getSetting({
            success: function (res) {
              if (res.authSetting['scope.userInfo']) {
                // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                wx.getUserInfo({
                  success: res => {
                    console.log('app.js', res);
                    wx.setStorageSync('wxUserInfo', res.userInfo);
                    var params = {
                      iv: res.iv,
                      encryptedData: res.encryptedData
                    }
                    wx.request({
                      url: API.URL.USER.MINI_WEIXINLOGIN,
                      data: {
                        code
                      },
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      method: "POST",
                      success: res => {
                        console.log('微信登陆接口成功', res);
                        params.openId = res.data.data.bussData.openId;
                        wx.setStorageSync("openId", params.openId);
                        that.saveUserInfo(params);
                        that.isSessionHave();                    
                      },
                      fail: res => {
                        console.log('微信登陆接口失败', res);
                      }
                    })
                  },
                  fail: function (res) {
                    console.log(res)
                  }
                })
              }
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },

  saveUserInfo: function (param) {
    let that = this;
    let url = API.URL.USER.SAVE_MINIUSERINFO;
    let local = this.getMyLocaltion();
    wx.request({
      url: 'https://invitedinner.icebartech.com/api/mini/user/saveMiniUserInfo',
      data: {
        openId: param.openId,
        encryptedData: param.encryptedData,
        iv: param.iv,
        longitude: local.longitude,
        latitude: local.latitude
      },
      method: "POST",
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: (data) => {
        console.log('保存用户信息成功', data);
      },
      fail: (data) => {
        console.log('保存用户信息失败', data);
      }
    })
  },
  getQQMap : function () {
    return QQMapWX;
  },
  setMyLocation : function (){
    let that = this;
    wx.getLocation({
      success: function (res) {
        wx.setStorage({
          key: 'latitude',
          data: res.latitude
        });
        wx.setStorage({
          key: 'longitude',
          data: res.longitude
        })
      },
      fail: function(res){
        that.showUserInfo('未授权，请前往设置页设置', 'none', 2000)
      }
    })
  },
  //得到用户位置
  getMyLocaltion : function () {
    let local = {}
    local.longitude = wx.getStorageSync('longitude');
    local.latitude = wx.getStorageSync('latitude')
    return local;
  },
  // 弹出提示框，title为提示内容，icon为弹框图表，duration为持续时间
  showUserInfo: function (title, icon, duration) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: duration
    })
  },
  //  前往弹框授权页面进行授权 
  isGoToGetScope: function() {
    let wxUserInfo = wx.getStorageSync('wxUserInfo');
    let latitude = wx.getStorageSync('latitude');
    if (wxUserInfo&&latitude){
      return false;
    }
    let that = this;
    wx.showModal({
      title: '友情提示',
      content: '须授权，是否前往设置',
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting["scope.userInfo"]){
                that.login();
              }
              if (res.authSetting["scope.userLocation"]){
                that.setMyLocation();
              }
            }
          })
        } else if (res.cancel) {
        }
      }
    })
  },
  // 是否手机账号已登陆，是返回true，否返回false
  isPhoneLogin: function () {
    let sesssionID = wx.getStorageSync("sessionId");
    if (sesssionID.length === 0) {
      return false;
    }
    return true;
  },
  isSessionHave : function() {
    let sesssionId = wx.getStorageSync("sessionId");
    wx.request({
      url: 'https://invitedinner.icebartech.com/api/mini/user/findMobile?sessionId='+sesssionId,
      method: "POST",
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: (res) => {
        console.log(res)
        if(res.data.status == '401'){
          wx.setStorageSync('sessionId', '');
          wx.setStorageSync('userInfo', '');
        } else if (res.data.status == 200){
          this.enterPage()
        }
      }
    })
  },
  enterPage() {
    util.httpbody({
      url: API.URL.SIGN.FIND_SING_LOG,
      success: res => {
        if (res.data.bussData.isSign != 'y'){
          wx.navigateTo({
            url: '../signIn/index',
          })
        }
      },
      fail: err => {
        console.log('ent err', err)
      }
    })
  },
  getRoomPage: function (page) {
    // "pages/chat/chat"
    return this.getPage(page)//聊天界面
  },
  getPage: function (pageName) {
    var pages = getCurrentPages()
    return pages.find(function (page) {
      return page.__route__ == pageName
    })
  },
  setChatMemberListCache(chatMemberName) {
    let chatMemberList = wx.getStorageSync('chatMemberList') || [];
    if (!chatMemberList.includes(chatMemberName)) {
      chatMemberList.push(chatMemberName);
    }
    console.log('chatMemberList', chatMemberList);
    wx.setStorage({
      key: 'chatMemberList',
      data: chatMemberList
    })
  },
})